/*
 * Copyright 2003-2007 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

package com.colony.channel;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;

import com.argot.TypeException;
import com.argot.TypeLibrary;
import com.argot.network.TypeEndPoint;
import com.colony.concurrent.ThreadActivator;

public class ChannelServer
{
	private ChannelServerBack _channelBack;
	private Vector _channels;
	
	public ChannelServer( TypeLibrary library, ThreadActivator threadActivator) 
	throws TypeException
	{
		_channelBack = new ChannelServerBack( this, library, threadActivator  );
		_channels = new Vector();
	}

	public ChannelServerBack getBack()
	{
		return _channelBack;
	}

	/**
	 * Used by a server application to create a channel to a client.
	 * The server begins writing to the end point.
	 * @return
	 */
	public synchronized Channel assignChannel()
	{
		ChannelInternal channel = new ChannelInternal();
		_channels.add( channel );
		int id = _channels.indexOf( channel ) + 1;
		channel.setId( id );
		
		return channel.getChannel();
	}
	
	public synchronized ChannelIdentifier assignChannel( InputStream in, OutputStream out )
	{
		ChannelInternal channel = new ChannelInternal( in, out );
		_channels.add( channel );
		int id = _channels.indexOf( channel ) + 1;
		return new ChannelIdentifier(id);
	}
	
	public synchronized Channel getChannel( int id )
	{
		id--;
		
		if ( id > _channels.size() )
			return null;
			
		ChannelInternal channel = (ChannelInternal) _channels.get( id );
		if ( channel == null )
			return null;
			
		return channel.getChannel();
	}
	
	protected synchronized TypeEndPoint getEndPoint( int id )
	{
		id--;
		
		if ( id > _channels.size() )
		{
			return null;
		}
		ChannelInternal channel = (ChannelInternal) _channels.get( id );
		if ( channel == null )
			return null;
			
		return channel.getEndPoint();
	}
}
